/**
 * 拖拽
 * @author xiaoxujs
 */


import type { DragEndEvent } from "@dnd-kit/core";
import { DndContext } from "@dnd-kit/core";
import { restrictToVerticalAxis } from "@dnd-kit/modifiers";
import {
    // arrayMove,
    SortableContext,
    useSortable,
    /*
    垂直列表使用verticalListSortingStrategy,
    横向列表使用horizontalListSortingStrategy
    */
    verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { Button, ConfigProvider, message, Table, TableColumnsType } from "antd";
import * as React from "react";
import { FC, useContext, useEffect, useMemo } from "react";
import { TableBoxNew } from "../../style";
import type { SyntheticListenerMap } from '@dnd-kit/core/dist/hooks/utilities';
import { HolderOutlined } from '@ant-design/icons';
import { useWindowFontSize } from "../../../../assets/fun/Antd/configprovider";
import { IWSDataSortList } from "../../../../type/cheliangpaidui";
import { postBaseSortSort } from "../../api";

interface RowContextProps {
    setActivatorNodeRef?: (element: HTMLElement | null) => void;
    listeners?: SyntheticListenerMap;
}

const RowContext = React.createContext<RowContextProps>({});
interface RowProps extends React.HTMLAttributes<HTMLTableRowElement> {
    'data-row-key': string;
}

const DragHandle: React.FC<{
    data: IWSDataSortList,
    setClickData: React.Dispatch<React.SetStateAction<IWSDataSortList | undefined>>
    setAddChangeModule: React.Dispatch<React.SetStateAction<boolean>>
    setChedaoId: React.Dispatch<React.SetStateAction<string | undefined>>;
    chedaoID: string;
}> = ({
    data,
    setClickData,
    setAddChangeModule,
    setChedaoId,
    chedaoID
}) => {
        const { setActivatorNodeRef, listeners } = useContext(RowContext);
        return (
            <>
                <Button
                    type="text"
                    size="small"
                    icon={<HolderOutlined />}
                    style={{ cursor: 'move' }}
                    ref={setActivatorNodeRef}
                    {...listeners}
                />
                <span className="iconfont" style={{ marginRight: '1rem' }} onClick={() => {
                    setClickData(data);
                    setAddChangeModule(true);
                    setChedaoId(chedaoID)

                }}>&#xe642;</span>
                <span>{data.plateColor + data.licensePlate}</span>
            </>

        );
    };

const Tuozhuai: FC<{
    listData: IWSDataSortList[];
    setClickData: React.Dispatch<React.SetStateAction<IWSDataSortList | undefined>>
    setListLoading: React.Dispatch<React.SetStateAction<boolean>>;
    setAddChangeModule: React.Dispatch<React.SetStateAction<boolean>>;
    setChedaoId: React.Dispatch<React.SetStateAction<string | undefined>>;
    chedaoID: string;
}> = ({
    listData,
    setClickData,
    setListLoading,
    setAddChangeModule,
    setChedaoId,
    chedaoID
}) => {
        const columns: TableColumnsType<IWSDataSortList> = [
            {
                key: 'sort', align: 'center', width: 80, render: (_, record) => <DragHandle
                    data={record}
                    setClickData={setClickData}
                    setAddChangeModule={setAddChangeModule}
                    setChedaoId={setChedaoId}
                    chedaoID={chedaoID}
                />
            },
            // { title: 'Name', dataIndex: 'name' },
        ];


        const [dataSource, setDataSource] = React.useState<IWSDataSortList[]>([]);
        useEffect(() => {
            if (listData) {
                let arr = [...listData];
                arr.shift();
                setDataSource(arr)
            }
        }, [listData])


        const onDragEnd = ({ active, over }: DragEndEvent) => {
            if (active.id !== over?.id) {
                console.log(active)
                console.log(over)
                let newActive = active as any;
                let newOver = over as any;
                // setDataSource((prevState) => {
                //     const activeIndex = prevState.findIndex((record) => record.id === active?.id);
                //     const overIndex = prevState.findIndex((record) => record.id === over?.id);
                //     return arrayMove(prevState, activeIndex, overIndex);
                // });
                ; (async () => {
                    setListLoading(true);
                    if (active && over) {
                        setListLoading(true);
                        const { code, msg } = await postBaseSortSort({
                            id: newActive.id,
                            upperId: newOver?.id
                        }) as { code: number; msg: string };
                        if (code === 20000) {
                            message.success('设置成功')
                        } else {
                            message.error(msg);
                            setListLoading(false);
                        }
                    }else{
                        setListLoading(false);
                    }
                })();
            }
        };
        const Row: React.FC<RowProps> = (props) => {
            const {
                attributes,
                listeners,
                setNodeRef,
                setActivatorNodeRef,
                transform,
                transition,
                isDragging,
            } = useSortable({ id: props['data-row-key'] });

            const style: React.CSSProperties = {
                ...props.style,
                transform: CSS.Translate.toString(transform),
                transition,
                ...(isDragging ? { position: 'relative', zIndex: 999 } : {}),
            };

            const contextValue = useMemo<RowContextProps>(
                () => ({ setActivatorNodeRef, listeners }),
                [setActivatorNodeRef, listeners],
            );

            return (
                <RowContext.Provider value={contextValue}>
                    <tr {...props} ref={setNodeRef} style={style} {...attributes} />
                </RowContext.Provider>
            );
        };
        return <DndContext modifiers={[restrictToVerticalAxis]} onDragEnd={onDragEnd}>
            <SortableContext items={dataSource.map((i) => i.id)} strategy={verticalListSortingStrategy}>
                <ConfigProvider theme={{
                    components: {
                        Table: {
                            headerColor: '#8B9BAC',
                            cellFontSize: useWindowFontSize(14),
                            cellPaddingBlock: 18
                        }
                    }
                }}>
                    <TableBoxNew>
                        <Table<IWSDataSortList>
                            rowKey="id"
                            components={{ body: { row: Row } }}
                            columns={columns}
                            dataSource={dataSource}
                            pagination={false}
                        />
                    </TableBoxNew>
                </ConfigProvider>
            </SortableContext>
        </DndContext>
    }

export default Tuozhuai;